<?php

/**
	Creatic Theme Library

	The contents of this file are subject to the terms of the GNU General
	Public License Version 2.0. You may not use this file except in
	compliance with the license. Any of the license terms and conditions
	can be waived if you get permission from the copyright holder.

	Copyright (c) 2011 Bandit Media
	Jermaine Marée

		@package FeatherTheme
		@version 1.1
**/

//! Creatic
class FeatherTheme extends FeatherBase {

	//@{ Theme details
	const
		THEME_Name = 'Creatic',
		THEME_Version = '1.1';
	//@}

	protected static
		//! Content width
		$content_width = 628,
		//! Option name
		$option_name = 'bandit_creatic',
		//! Theme options
		$option,
		//! Theme Language
		$lang;

	/**
		Get theme option
			@return mixed
			@param $key string
			@public
	**/
	static function get_option($key) {
		$value = isset(self::$option[$key])?self::$option[$key]:FALSE;
		return $value;
	}

	/**
		Get lang option
			@return string
			@param $key string
			@public
	**/
	static function get_lang($key,$default='') {
		$lang = isset(self::$lang[$key])?self::$lang[$key]:'';
		$value = ($lang!='')?$lang:$default;
		return $value;
	}

	/**
		Initialize Theme
			@public
	**/
	static function init() {
		// Check Feather version
		if(version_compare(FeatherBase::TEXT_Version,'1.2.1') < 0) {
			$message = 'Creatic requires Feather 1.2.1 or greater. Please '.
				'upgrade the Feather plugin.';
			if(is_admin()) {
				if(version_compare('1.2',FeatherBase::TEXT_Version) <= 0) {
					self::add_notice($message,'error');
				} else {
					self::$vars['ERROR'] = $message;
				}
			} else {
				// Exclude login,register pages
				$exclude=array('wp-login.php','wp-register.php');
				if(!in_array(self::$vars['PAGENOW'],$exclude)) {
					wp_die($message);
				}
			}
			return;
		}
		// Content width
		global $content_width;
		if(!isset($content_width)) { $content_width = self::$content_width; }
		// i18n
		add_action('after_setup_theme',__CLASS__.'::i18n');
		// Theme options
		self::$option = get_option(self::$option_name);
		$feather = get_option('feather');
		// If no options, set defaults
		if(!self::$option || !is_array(self::$option)) {
			self::$option = array(
				'version' 		 		=> self::THEME_Version,
				'comments_pages' 		=> '1',
				'blog_index_content'	=> 'content'
			);
			update_option(self::$option_name,self::$option);
			// Set feather options
			$feather = get_option('feather');
			if($feather || !is_array($feather)) {
				$feather['auto_feed_links'] = '1';
				$feather['post_thumbnails'] = '1';
				update_option('feather',$feather);
			}
		}
		// Post Thumnails
		add_theme_support('post-thumbnails');
		// Theme language
		self::$lang = get_option('bandit_language');
		if(!self::$lang) { update_option('bandit_language',''); }
		// Theme activation
		if('themes.php'==self::$vars['PAGENOW'] && isset($_GET['activated'])) {
			self::activation();
		}
		// Admin methods
		if(is_admin()) {
			// Upgrade
			self::upgrade();
			// Boot admin
			require(FEATHER_THEME_PATH.'lib/bandit-admin.php');
			BanditAdmin::boot();
		}
		// Ajax
		require(FEATHER_THEME_PATH.'lib/bandit-ajax.php');
		BanditAjax::init();
		// Non-admin methods
		if(!is_admin()) {
			// Load Helper
			require(FEATHER_THEME_PATH.'lib/bandit-helper.php');
			// Shortcodes
			self::shortcodes();
			// Theme actions
			self::actions();
		}
	}

	/**
		i18n
			@public
	**/
	static function i18n() {
		// Theme's translated strings
		load_theme_textdomain('creatic',get_template_directory().'/languages');
	}

	/**
		Activation
			@private
	**/
	private static function activation() {
		// Create bandit_images table
		self::create_images_table();
	}

	/**
		Upgrade
			@private
	**/
	private static function upgrade() {
		$current_version = self::get_option('version');
		// Do we need to upgrade?
		if(version_compare($current_version,self::TEXT_Version) < 0) {
			require(FEATHER_THEME_PATH.'lib/bandit-upgrade.php');
			BanditUpgrade::init();
		}
	}

	/**
		Create table
			@public
	**/
	static function create_images_table() {
		global $wpdb;
		$table_name='bandit_images';
		// Create dynamic images table if it doesn't exist
		if(!$wpdb->get_var("show tables like '".$table_name."'")) {
			$sql = "CREATE TABLE  ".$table_name." (
							image_id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
							post_id bigint(20) unsigned NOT NULL,
							image_file varchar(255) DEFAULT '' NOT NULL,
							UNIQUE KEY image_id (image_id)
							) CHARSET=utf8;";
			require_once(ABSPATH.'wp-admin/includes/upgrade.php');
			dbDelta($sql);
		}
	}

	/**
		Theme styles
			@public
	**/
	static function styles() {
		// Styles directory
		$styles_dir=get_template_directory().'/styles';
		// Default style
		$default=array('0'=>'Default');
		// Empty array
		$styles=array();
		if(is_dir($styles_dir) && $handle=opendir($styles_dir)) {
			while(false !== ($file=readdir($handle))) {
				if($file!="." && $file!=".." && is_file($styles_dir.'/'.$file)) {
					$tmp = new SplFileObject($styles_dir.'/'.$file);
					$tmp->seek(1);
					$name=substr(esc_html($tmp->current()),7);
					$styles[$file]=$name;
				}
			}
			closedir($handle);
			// Combine arrays
			if($styles) {
				asort($styles);
				$styles=$default+$styles;
			}
		}
		return $styles?$styles:FALSE;
	}

	/**
		Shortcodes
			@private
	**/
	private static function shortcodes() {
		require(FEATHER_THEME_PATH.'lib/bandit-shortcode.php');
		$shortcodes=array_diff(get_class_methods('BanditShortcode'),
			get_class_methods('FeatherBase'));
		foreach($shortcodes as $shortcode)
			add_shortcode($shortcode,'BanditShortcode::'.$shortcode);
	}

	/**
		Theme actions
			@private
	**/
	private static function actions() {
		// Theme javascript
		add_action('template_redirect',__CLASS__.'::javascript');
		// Theme filters
		add_action('after_setup_theme',__CLASS__.'::filters');
		// Add action to output to head
		add_action('wp_head',__CLASS__.'::wp_head');
		// Add action to output to footer
		add_action('wp_footer',__CLASS__.'::wp_footer');
	}

	/**
		Javascript
			@public
	**/
	static function javascript() {
		// Get page template
		$pagetmpl = is_page()?basename(get_page_template()):'';

		// Default scripts
		$scripts=array('jquery','jquery-ui-core','jquery-ui-tabs','slides','masonry');

		// Enqueue carouFredSel
		if('template-front.php' == $pagetmpl) {
			$scripts[]='caroufredsel';
		}
	
		// Enqueue jplayer
		if((is_home() || is_single() || is_archive()) && 'portfolio'!=get_post_type())
			$scripts[]='jplayer';

		// Enqueue prettyPhoto
		if('portfolio'==get_post_type() && is_tax('portfolio_category')) {
			// Get portfolio category
			$term=get_term_by('slug',get_query_var( 'term' ),get_query_var('taxonomy'));
			// Check if lightbox enabled
			if(self::get_option('theme_portfolio_'.$term->slug.'_lightbox')) {
				wp_enqueue_style('prettyPhoto',get_template_directory_uri().
					'/css/prettyPhoto/prettyPhoto.css',FALSE,'3.1.3');
				$scripts[]='prettyPhoto';
			}
		}

		// Add prettyPhoto to other pages
		if('portfolio'!=get_post_type()) {
			wp_enqueue_style('prettyPhoto',get_template_directory_uri().
					'/css/prettyPhoto/prettyPhoto.css',FALSE,'3.1.3');
			$scripts[]='prettyPhoto';
		}

		// Load theme script
		wp_enqueue_script('bandit-theme',get_template_directory_uri().'/js/jquery.theme.js',$scripts,'1.0');
		// AJAX url variable
		wp_localize_script('bandit-theme','bandit',
			array(
				'ajaxurl'=>admin_url('admin-ajax.php'),
				'ajaxnonce' => wp_create_nonce('wpb-creatic-ajax-nonce')
			)
		);
	}

	/**
		Filters
			@public
	**/
	static function filters() {
		$filters = self::get_config('FILTERS');
		if($filters) {
			foreach($filters as $tag=>$function) {
				if(!isset($function['priority']))
					$function['priority']=10;
				if(!isset($function['args']))
				 $function['args']=1;
				add_filter($tag,__CLASS__.'::'.$function['name'],
					$function['priority'],$function['args']);
			}
		}
		// Feed link filter
		if(self::get_option('feed_url'))
			add_filter('feed_link',__CLASS__.'::filter_feedlink',10,2);
	}

	/**
		Theme feed link filter
			@public
	**/
	static function filter_feedlink($output,$feed) {
		$feed_url=self::get_option('feed_url');
		$feed_array = array('rss'=>$feed_url, 'rss2'=>$feed_url,
			'atom'=>$feed_url, 'rdf'=>$feed_url, 'comments_rss2'=>'');
		$feed_array[$feed]=$feed_url;
		return $feed_array[$feed];
	}

	/**
		Theme WP Head
			@public
	**/
	static function wp_head() {
		// Analytics script
		if(self::get_option('analytics_script'))
			if('header'===self::get_option('analytics_location'))
				echo self::get_option('analytics_script')."\n";
	}

	/**
		Theme WP Footer
			@public
	**/
	static function wp_footer() {
		// Analytics script
		if(self::get_option('analytics_script'))
			if('footer'===self::get_option('analytics_location'))
				echo self::get_option('analytics_script')."\n";
	}

	/**
		Portfolio category fields
			@public
	**/
	static function print_field_portcat_templates($args) {
		// Template fields
		$output='<select name="bandit_creatic['.$args['id'].']">';
		foreach($args['choices'] as $id=>$label)
			$output.='<option value="'.$id.'" '.selected($id,self::get_option($args['id']),FALSE).'>'.$label.'</option>';
		$output.='</select>';

		// Category items per page
		$output.='&nbsp;&nbsp; <select name="bandit_creatic['.$args['id'].'_num]">';
		$output.='<option value="0" '.selected('0',self::get_option($args['id'].'_num'),FALSE).'>All</option>';
		for($i=1;$i<=40;$i++)
			$output.='<option value="'.$i.'" '.selected($i,self::get_option($args['id'].'_num'),FALSE).'>'.$i.'</option>';
		$output.='</select> Per Page';

		// Lightbox
		$output.='<div style="margin-top:10px;">';
		$output.='<input type="checkbox" name="bandit_creatic['.$args['id'].'_lightbox]" value="1" '.
			checked(self::get_option($args['id'].'_lightbox'), 1, FALSE).' /> Enable Lightbox</div>';
		$output.='<hr style="border-top:1px dotted #cfcfcf;border-bottom:1px dotted #fff;border-left:none;margin-left:-220px">';
		echo $output;
	}

	/**
		Portfolio template guide
			@public
	**/
	static function print_field_port_template_guide($args) {
		$url = FEATHER_THEME_URL.'assets/img';
?>
		<ul class="bandit_port_tmpl_guide">
			<li><img src="<?php echo $url; ?>/1.png"><br><strong>1</strong> - 688x516px</li>
			<li><img src="<?php echo $url; ?>/2.png"><br><strong>2</strong> - 333x333px</li>
			<li><img src="<?php echo $url; ?>/3.png"><br><strong>3</strong> - 215x215px</li>
			<li><img src="<?php echo $url; ?>/4.png"><br><strong>4</strong> - 156x156px</li>
			<li><img src="<?php echo $url; ?>/5.png"><br><strong>5</strong> - 688x370px</li>
			<li class="last"><img src="<?php echo $url; ?>/6.png"><br><strong>6</strong> - 333x220px</li>
			<li><img src="<?php echo $url; ?>/7.png"><br><strong>7</strong> - 215x300px</li>
			<li><img src="<?php echo $url; ?>/8.png"><br><strong>8</strong> - 156x220px</li>
			<li><img src="<?php echo $url; ?>/9.png"><br><strong>9</strong> - 333x420px</li>
			<li><img src="<?php echo $url; ?>/10.png"><br><strong>10</strong> - 215x170px</li>
			<li><img src="<?php echo $url; ?>/11.png"><br><strong>11</strong> - 333x220px</li>
			<li class="last"><img src="<?php echo $url; ?>/12.png"><br><strong>12</strong> - 97x97px</li>
		</ul>
<?php
	}

	/**
		Creatic sidebar links
			@public
	**/
	static function print_field_sidebar_links($args) {
		// Build item id's
		$id_text='theme_sidebar_text'.$args['id'];
		$id_icon='theme_sidebar_icon'.$args['id'];
		$id_link='theme_sidebar_link'.$args['id'];
		$id_custom='theme_sidebar_custom'.$args['id'];
		// Icon List
		$icons=array(
			'basket.png'=>'Basket',
			'bubbles.png'=>'Bubbles',
			'camera.png'=>'Camera',
			'chain.png'=>'Chain',
			'facebook.png'=>'Facebook',
			'game.png'=>'Game',
			'globe.png'=>'Globe',
			'google.png'=>'Google',
			'heart.png'=>'Heart',
			'home.png'=>'Home',
			'info.png'=>'Info',
			'letter.png'=>'Letter',
			'movie.png'=>'Movie',
			'music.png'=>'Music',
			'pen.png'=>'Pen',
			'plus.png'=>'Plus',
			'quote.png'=>'Quote',
			'rss.png'=>'RSS',
			'search.png'=>'Search',
			'twitter.png'=>'Twitter'
		);

		// Build title field
		$output='<label>Title:</label> <input name="bandit_creatic['.$id_text.']" type="text" value="'.self::get_option($id_text).'" id="bandit_creatic['.$id_text.']" class="medium-text" style="margin-right:15px">';
		// Build icon field
		$output.='<label>Icon:</label> <select name="bandit_creatic['.$id_icon.']">';
		foreach($icons as $id=>$label)
			$output.='<option value="'.$id.'" '.selected($id,self::get_option($id_icon),FALSE).'>'.$label.'</option>';
		$output.='</select><br/>';
		// Link field
		$output.='<div style="margin-top:10px;"><label>Link:</label> <input name="bandit_creatic['.$id_link.']" type="text" value="'.self::get_option($id_link).'" id="bandit_creatic['.$id_link.']" class="regular-text"></div>';
		// Custom Image
		$output.='<div style="margin-top:10px;">';
		$output.='<label>Custom Image:</label> <input id="bandit_creatic['.$id_custom.']" type="text" name="bandit_creatic['.$id_custom.']" class="medium-text" value="'.self::get_option($id_custom).'">';
		$output.='<input id="bandit_creatic['.$id_custom.'_button]" class="button-secondary feather-image-button" type="button" value="Select Image" data-id="custom_logo"></div>';
		$output.='<hr style="border-top:1px dotted #cfcfcf;border-bottom:1px dotted #fff;border-left:none;margin-left:-220px;margin-top:10px">';
		echo $output;
	}

	/**
		Front Slider Meta
			@public
	**/
	static function front_slider_meta($post,$meta) {
		// Begin table
		$output = '<table class="form-table">';
		// Loop through fields
		foreach($meta['args'] as $field) {
			// Get value
			$value = get_post_meta($post->ID,$field['id'],TRUE);
			// Begin table row
			$output .= '<tr>';
			$output .= '<th><label>'.$field['label'].'</label></th>';
			$output .= '<td>';
			// Set attributes
			$attrs = array(
				'id'	=> $field['id'],
				'name'	=> $field['id']
			);
			$output .= FeatherForm::select($attrs,$value,$field['choices']);
			$output .= '<a href="'.admin_url().'themes.php?page=banditmod&tab=sliders" style="margin-left:10px">Add / Edit / Delete</a>';
			// End table row
			$output .= '</td></tr>';
		}
		// End table
		$output .= '</table>';
		// Print fields
		echo $output;
	}

	/**
		Widget meta box
			@public
	**/
	static function front_widget_meta($post,$meta) {
		// Begin table
		$output = '<table class="form-table">';
		// Begin table row
		$output .= '<tr>';
		$output .= '<th><label>Widgets</label></th>';
		$output .= '<td>';
		// Field
		$output .= '<a href="'.admin_url().'widgets.php">Add / Edit / Delete</a>';
		// End table row
		$output .= '</td></tr>';
		// End table
		$output .= '</table>';
		echo $output;
	}

}